package com.vone.until.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Connectiondb {
	ResultSet res = null;

	/**
	 * 加载驱动文件
	 */
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取数据库连接对象的公共方法
	 */
	public static Connection getConnection() {
		String jdbcUrl = MyJdbc.getJdbcurl();
		String user = MyJdbc.getUser();
		String pwd = MyJdbc.getPwd();
		//System.out.println("\n数据库连接信息：\n" + jdbcUrl + "\n" + user + "\n" + pwd + "\n");
		//System.out.println("\n数据库连接信息：\n" + jdbcUrl + "\n" + user + "\n" + pwd + "\n");
		try {
			return DriverManager.getConnection(jdbcUrl, user, pwd);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 关闭数据库连接对象，释放资源的公共方�?
	 * 
	 * @param con
	 *            数据库连接对�?
	 * @param st
	 *            语句执行对象
	 * @param rs
	 *            结果集对�?
	 */
	public static void closeDb(Connection con, Statement st, ResultSet rs) {
		if (rs != null)
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if (st != null)
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if (con != null)
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	// 查询
	public ResultSet Search(String sql, String str[]) {
		Connection con = getConnection();// 获取数据库连接对�?
		PreparedStatement ps = null; // 获取语句执行对象
		try {
			PreparedStatement pst = con.prepareStatement(sql);
			if (str != null) {
				for (int i = 0; i < str.length; i++) {
					pst.setString(i + 1, str[i]);
				}
			}
			res = pst.executeQuery();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}

	/**
	 * 执行对数据库添加，删除，修改的公共方�?
	 * 
	 * @param sql
	 *            要执行的SQL语句insert,update,delete
	 * @param objs
	 *            要填充到SQL中的参数�?
	 * @return
	 */
	public static boolean updateDb(String sql, Object[] objs) {
		Connection con = getConnection();// 获取数据库连接对�?
		PreparedStatement ps = null; // 获取语句执行对象
		try {
			ps = con.prepareStatement(sql);
			if (objs != null && objs.length > 0) {// 有占位符
				for (int i = 0; i < objs.length; i++) {
					if (objs[i] == null)
						objs[i] = "";
					ps.setObject(i + 1, objs[i]);
				}
			}
			if (ps.executeUpdate() > 0) {// 执行更新操作
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeDb(con, ps, null);// 关闭连接，释放资�?
		}
		return false;
	}
}